<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2017/8/30
 * Time: 15:31
 */

namespace frontend\modules\common\controllers;

use frontend\modules\common\logic\DownLoad;
use frontend\modules\common\models\BaseHelper;
use frontend\modules\common\models\BaseParam;
use frontend\modules\common\models\Image;
use frontend\modules\common\models\UploadExcel;
use frontend\modules\resource\logic\BranchLogic;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class BaseController extends Controller
{
    public $layout;
    public $branchId;
    public $branchTitle;
    protected $managerName;
    public $type;
    public $specialId;

    /**
     * @throws \yii\base\ExitException
     */
    public function init()
    {
        if (Yii::$app->user->isGuest) {
            $this->redirect('site/login');
            Yii::$app->end();
        }
    }

    public function branchAdmin()
    {
        $this->branchId = Yii::$app->session->get('branchAdminBId');
        $this->managerName = Yii::$app->session->get('branchAdminName');
    }

    /**
     * 校验分馆id
     * @throws \yii\base\ExitException
     */
    public function checkBrId($session_name = 'br_id', $default_url = '/resource/branch')
    {
        $res = Yii::$app->request->get('br_id');
        //如果没有定义 br_id返回分馆页
        //如果传递分馆id则存上
        if ($res) {
            $info = (new BranchLogic())->getBranchInfo($res);
            if (empty($info)) {
                $this->redirect($default_url);
                Yii::$app->end();
            }
            Yii::$app->session->set($session_name, $res);
            Yii::$app->session->set($session_name . 'title', $info['title']);

            $this->branchId = $res;
            $this->branchTitle = $info['title'];
        } else {
            $this->branchId = Yii::$app->session->get($session_name);
            $this->branchTitle = Yii::$app->session->get($session_name . 'title');
            if (empty($this->branchId)) {
                $this->redirect($default_url);
                Yii::$app->end();
            }
        }
    }

    /**
     * 校验资源类型 for 所有资源
     * @throws \yii\base\ExitException
     */
    public function checkType($session_name = 'all_resource_type', $default_url = '/resource/resource?type=1')
    {

        $res = Yii::$app->request->get('type');

        //如果没有定义 br_id返回分馆页
        //如果传递分馆id则存上
        if ($res) {
            if (!in_array($res, [1, 2, 3, 4, 5])) {
                $this->redirect($default_url);
                Yii::$app->end();
            }
            Yii::$app->session->set($session_name, $res);
            $this->type = $res;
        } else {
            $this->type = Yii::$app->session->get($session_name);
            if (empty($this->type)) {
                $this->redirect($default_url);
                Yii::$app->end();
            }
        }
    }

    /**
     * 校验资源类型 for 分馆资源
     * @throws \yii\base\ExitException
     */
    public function checkSpecialId()
    {

        $res = Yii::$app->request->get('sp_id');

        //如果没有定义 br_id返回分馆页
        //如果传递分馆id则存上
        if ($res && is_numeric($res)) {
            Yii::$app->session->set('special_id', $res);
            $this->specialId = $res;
        } else {
            $this->specialId = Yii::$app->session->get('special_id');
            if (empty($this->specialId)) {
                $this->redirect('/resource/special');
                Yii::$app->end();
            }
        }
    }

    /**不同视图配置不同模板
     * @param string $view
     * @param array $params
     * @return string
     */
    public function render($view, $params = [])
    {
        if ($view == 'index' || $view == 'user') {

            $this->layout = '../../../../views/layouts/main_index';
        } else if (in_array($view, ['create', 'update', 'view'])) {

            $this->layout = '../../../../views/layouts/main_content';
        } else {

            $this->layout = '../../../../views/layouts/main';
        }
        return parent::render($view, $params);
    }

    /**
     * @param array $data_to_merge
     * @return string
     */
    protected function suc($data_to_merge = [])
    {
        $data = ['status' => 200];
        $data = array_merge($data, $data_to_merge);
        return json_encode($data, 256);
    }

    /**
     * @param null $msg
     * @return string
     */
    protected function err($msg = null)
    {
        if (is_array($msg))
            return json_encode(['status' => $msg[0], 'msg' => $msg[1]], 256);
        return json_encode(['status' => 0, 'msg' => $msg], 256);
    }

    //操作完成辅助页面
    public function actionFinish()
    {
        return $this->render('../../../common/views/base/_finish');
    }

    /**上传图片
     * @return string
     */
    public function actionUploadImg()
    {
        try {
            if (!isset($_FILES['image']) || empty($_FILES['image'])) {
                throw new NotFoundHttpException('image required');
            }
            $res = (new Image())->uploadFile('image');
            return $this->suc(['data' => $res]);
        } catch (NotFoundHttpException $e) {
            return $this->err($e->getMessage());
        }
    }

    /**下载模板
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \yii\base\Exception
     */
    public function actionTemplate()
    {
        $temp_type = Yii::$app->request->get('type');
        (new DownLoad())->DownloadExcelTemp($temp_type);
    }

    /**
     * 上传表格
     * @return string
     * @throws \yii\base\ExitException
     */
    public function actionUploadFile()
    {

        if (!isset($_FILES['excel']) || empty($_FILES['excel'])) {
            BaseHelper::Error('file required');
        }
        $res = (new UploadExcel(BaseParam::$excelSavePath))->Upload($_FILES);
        return $this->suc(['data' => $res, 'msg' => '上传完成']);
    }

}